package org.sakila.controller;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.java.Log;
import org.sakila.entities.CommonResult;
import org.sakila.entities.Film;
import org.sakila.service.SakilaService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Log
public class SakilaController {

    @Resource
    private SakilaService sakilaService;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/film/create")
    public CommonResult create(@RequestBody Film film) {

        int result = sakilaService.createFilm(film);
        log.info("插入结果" + result);

        if (result > 0) {
            return new CommonResult(200, "插入数据库成功" + serverPort, result);
        } else {
            return new CommonResult(444, "插入数据库失败" + serverPort, null);
        }
    }

    @GetMapping("/film/get/{id}")
    public CommonResult getFilmById(@PathVariable("id") Long id) {
        Film film = sakilaService.getFilmById(id);
        log.info("film:" + film);
        if (film != null) {
            return new CommonResult(200, "获得数据成功" + serverPort, film);
        } else {
            return new CommonResult(444, "获得数据失败" + serverPort, null);
        }
    }

    @GetMapping("/film/getFilms/{start}/{size}")
    public CommonResult<?> getFilms(@PathVariable(value = "start", required = false) Integer start, @PathVariable(value = "size", required = false) Integer size) {
        start = start == null ? 0 : start;
        size = size == null ? 10 : size;
        List<Film> films = sakilaService.getFilms(start, size);
        if (CollUtil.isEmpty(films)) {
            return new CommonResult<>(200, "获取数据失败" + serverPort, null);
        } else {
            return new CommonResult<>(200, "获取数据成功" + serverPort, films);
        }
    }
}
